<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>全局前置守卫</title>
</head>

<body>
    <div id="app">
        <router-link to="/" tag="button">首页</router-link>
        <router-link to="/news">新闻</router-link>
        <router-link to="/login">登录</router-link>
        <router-view></router-view>
    </div>
    <template id="tem1">
        <h2>这是首页</h2>
    </template>
    <template id="tem2">
        <div>这是新闻页面</div>
    </template>
    <template id="tem3">
        <h2>登录页面</h2>
    </template>
</body>

</html>
<script src="https://cdn.bootcss.com/vue/2.6.11/vue.min.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
    const Home = {
        template: "#tem1"
    }
    const News = {
        template: "#tem2"
    }
    const Login = {
        template: "#tem3"
    }
    const routes = [{
        path: "/",
        component: Home
    }, {
        path: "/news",
        component: News
    }, {
        path: "/login",
        component: Login
    }]
    const router = new VueRouter({
        routes
    })
    new Vue({
        el: "#app",
        router: router,
    })
    /* 全局前置守卫 */
    router.beforeEach((to, from, next) => {
        if (to.path == "/login") {
            next();
        } else {
            /* 是否登录 */
            let isLogin = false;
            if (isLogin) {
                console.log("已经登录");
                next();
            } else {
                console.log("没有登录，请先登录")
                next({ path: "/login" });
            }
        }
    })
</script>